import { useState, useEffect, useCallback } from 'react';
import {
  X,
  Play,
  Download,
  Clock,
  Film,
  FileText,
  AlertCircle,
  CheckCircle,
  XCircle,
  Copy,
  ExternalLink,
} from 'lucide-react';
import type { Video } from '../types/video';
import { VideoStatus } from '../types/video';
import videoService from '../services/videoService';
import { toast } from '../stores/toastStore';

interface VideoDetailProps {
  videoId: string;
  onClose: () => void;
}

export default function VideoDetail({ videoId, onClose }: VideoDetailProps) {
  const [video, setVideo] = useState<Video | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('info');

  const loadVideoDetail = useCallback(async () => {
    try {
      setLoading(true);
      const data = await videoService.getVideoDetail(videoId);
      setVideo(data);
    } catch (error) {
      console.error('Failed to load video detail:', error);
    } finally {
      setLoading(false);
    }
  }, [videoId]);

  useEffect(() => {
    loadVideoDetail();
  }, [loadVideoDetail]);

  const handleDownload = async () => {
    if (!video?.video_url) return;

    try {
      const link = document.createElement('a');
      link.href = video.video_url;
      link.download = `${video.video_title || video.video_id}.mp4`;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('Failed to download video:', error);
      toast.error('视频下载失败，请稍后重试');
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('zh-CN');
  };

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case VideoStatus.COMPLETED:
        return <CheckCircle className="w-5 h-5 text-green-500" />;
      case VideoStatus.PROCESSING:
        return <Clock className="w-5 h-5 text-blue-500 animate-spin" />;
      case VideoStatus.FAILED:
        return <XCircle className="w-5 h-5 text-red-500" />;
      case VideoStatus.DRAFT:
        return <FileText className="w-5 h-5 text-gray-500" />;
      default:
        return <AlertCircle className="w-5 h-5 text-yellow-500" />;
    }
  };

  if (loading) {
    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!video) {
    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg p-6">
          <p className="text-red-500">视频详情加载失败</p>
          <button onClick={onClose} className="mt-4 px-4 py-2 bg-gray-600 text-white rounded-lg">
            关闭
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg w-full max-w-5xl h-[85vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="p-6 border-b flex justify-between items-center">
          <div className="flex items-center gap-4">
            <h2 className="text-xl font-bold text-gray-900">{video.video_title || '无标题'}</h2>
            <div className="flex items-center gap-2">
              {getStatusIcon(video.status)}
              <span className="text-sm text-gray-700">{video.status}</span>
            </div>
          </div>
          <button onClick={onClose} className="text-gray-500 hover:text-gray-700 cursor-pointer">
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 flex overflow-hidden">
          {/* Video Preview */}
          <div className="w-3/5 bg-black flex items-center justify-center">
            {video.status === VideoStatus.COMPLETED && video.video_url ? (
              <video controls className="max-w-full max-h-full" poster={video.thumbnail_url}>
                <source src={video.video_url} type="video/mp4" />
                您的浏览器不支持视频播放
              </video>
            ) : video.thumbnail_url ? (
              <img
                src={video.thumbnail_url}
                alt={video.video_title}
                className="max-w-full max-h-full object-contain"
              />
            ) : (
              <div className="text-white text-center">
                <Film className="w-16 h-16 mx-auto mb-4 opacity-50" />
                <p className="opacity-50">
                  {video.status === VideoStatus.PROCESSING ? '视频处理中...' : '暂无预览'}
                </p>
              </div>
            )}
          </div>

          {/* Info Panel */}
          <div className="w-2/5 bg-gray-50 flex flex-col">
            {/* Tabs */}
            <div className="flex border-b bg-white">
              <button
                onClick={() => setActiveTab('info')}
                className={`flex-1 px-4 py-3 text-sm font-medium cursor-pointer ${
                  activeTab === 'info'
                    ? 'text-blue-600 border-b-2 border-blue-600'
                    : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                基本信息
              </button>
              <button
                onClick={() => setActiveTab('details')}
                className={`flex-1 px-4 py-3 text-sm font-medium cursor-pointer ${
                  activeTab === 'details'
                    ? 'text-blue-600 border-b-2 border-blue-600'
                    : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                详细信息
              </button>
              {video.error && (
                <button
                  onClick={() => setActiveTab('error')}
                  className={`flex-1 px-4 py-3 text-sm font-medium cursor-pointer ${
                    activeTab === 'error'
                      ? 'text-blue-600 border-b-2 border-blue-600'
                      : 'text-gray-600 hover:text-gray-900'
                  }`}
                >
                  错误信息
                </button>
              )}
            </div>

            {/* Tab Content */}
            <div className="p-6 space-y-4 flex-1 overflow-y-auto">
              {activeTab === 'info' && (
                <>
                  <div>
                    <label className="text-sm text-gray-700">视频ID</label>
                    <div className="flex items-center gap-2 mt-1">
                      <p className="text-sm font-mono text-gray-900">{video.video_id}</p>
                      <button
                        onClick={() => copyToClipboard(video.video_id)}
                        className="text-gray-400 hover:text-gray-600 cursor-pointer"
                      >
                        <Copy className="w-4 h-4" />
                      </button>
                    </div>
                  </div>

                  <div>
                    <label className="text-sm text-gray-700">类型</label>
                    <p className="mt-1 text-gray-900">{video.type}</p>
                  </div>

                  <div>
                    <label className="text-sm text-gray-700">时长</label>
                    <p className="mt-1 text-gray-900">
                      {video.duration > 0 ? formatDuration(video.duration) : '未知'}
                    </p>
                  </div>

                  <div>
                    <label className="text-sm text-gray-700">创建时间</label>
                    <p className="mt-1 text-gray-900">{formatDate(video.created_at)}</p>
                  </div>

                  <div>
                    <label className="text-sm text-gray-700">最后同步</label>
                    <p className="mt-1 text-gray-900">
                      {new Date(video.last_sync_at).toLocaleString('zh-CN')}
                    </p>
                  </div>

                  {video.folder_id && (
                    <div>
                      <label className="text-sm text-gray-700">文件夹ID</label>
                      <p className="mt-1 font-mono text-sm text-gray-900">{video.folder_id}</p>
                    </div>
                  )}
                </>
              )}

              {activeTab === 'details' && (
                <>
                  {video.video_url && (
                    <div>
                      <label className="text-sm text-gray-700">视频URL</label>
                      <div className="mt-1">
                        <a
                          href={video.video_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 text-sm break-all flex items-center gap-1"
                        >
                          {video.video_url}
                          <ExternalLink className="w-3 h-3 flex-shrink-0" />
                        </a>
                      </div>
                    </div>
                  )}

                  {video.thumbnail_url && (
                    <div>
                      <label className="text-sm text-gray-700">缩略图URL</label>
                      <div className="mt-1">
                        <a
                          href={video.thumbnail_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 text-sm break-all flex items-center gap-1"
                        >
                          {video.thumbnail_url}
                          <ExternalLink className="w-3 h-3 flex-shrink-0" />
                        </a>
                      </div>
                    </div>
                  )}

                  {video.gif_url && (
                    <div>
                      <label className="text-sm text-gray-700">GIF URL</label>
                      <div className="mt-1">
                        <a
                          href={video.gif_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 text-sm break-all flex items-center gap-1"
                        >
                          {video.gif_url}
                          <ExternalLink className="w-3 h-3 flex-shrink-0" />
                        </a>
                      </div>
                    </div>
                  )}

                  {video.caption_url && (
                    <div>
                      <label className="text-sm text-gray-700">字幕URL</label>
                      <div className="mt-1">
                        <a
                          href={video.caption_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 text-sm break-all flex items-center gap-1"
                        >
                          {video.caption_url}
                          <ExternalLink className="w-3 h-3 flex-shrink-0" />
                        </a>
                      </div>
                    </div>
                  )}

                  {video.video_url_caption && (
                    <div>
                      <label className="text-sm text-gray-700">带字幕视频URL</label>
                      <div className="mt-1">
                        <a
                          href={video.video_url_caption}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 text-sm break-all flex items-center gap-1"
                        >
                          {video.video_url_caption}
                          <ExternalLink className="w-3 h-3 flex-shrink-0" />
                        </a>
                      </div>
                    </div>
                  )}

                  {video.callback_id && (
                    <div>
                      <label className="text-sm text-gray-700">回调ID</label>
                      <p className="mt-1 font-mono text-sm text-gray-900">{video.callback_id}</p>
                    </div>
                  )}
                </>
              )}

              {activeTab === 'error' && video.error && (
                <div>
                  <label className="text-sm text-gray-700">错误详情</label>
                  <div className="mt-2 p-3 bg-red-50 border border-red-200 rounded-lg">
                    <pre className="text-sm text-red-800 whitespace-pre-wrap">
                      {typeof video.error === 'string'
                        ? video.error
                        : JSON.stringify(video.error, null, 2)}
                    </pre>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="p-6 border-t flex justify-between items-center">
          <div className="flex gap-2">
            {video.status === VideoStatus.COMPLETED && video.video_url && (
              <>
                <button
                  onClick={() => window.open(video.video_url, '_blank')}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2 cursor-pointer"
                >
                  <Play className="w-4 h-4" />
                  在新窗口播放
                </button>
                <button
                  onClick={handleDownload}
                  className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2 cursor-pointer"
                >
                  <Download className="w-4 h-4" />
                  下载视频
                </button>
              </>
            )}
          </div>
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 cursor-pointer"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  );
}
